package ace.tool.generate.code.impl.resolver.ui.resolver;

import ace.tool.generate.code.impl.manager.common.EntityModelManager;
import ace.tool.generate.code.impl.resolver.ui.model.bo.UiMockServerApiClassInfo;
import ace.tool.generate.code.impl.resolver.ui.model.bo.UiMockServerApiIndexClassInfo;
import ace.tool.generate.code.impl.resolver.ui.model.bo.UiProjectCommonInfo;
import ace.tool.generate.code.impl.resolver.ui.model.dto.UiClassFileInfo;
import ace.tool.generate.code.impl.service.model.input.GenerateInput;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.apache.commons.text.StringSubstitutor;

/**
 * @author caspar
 * @date 2023/11/17 10:34
 */
@RequiredArgsConstructor
public class UiMockServerApiIndexClassInfoResolver {
  private final GenerateInput input;
  private final UiProjectCommonInfo commonInfo;
  private final List<UiMockServerApiClassInfo> uiMockServerApiClassInfos;
  private final EntityModelManager entityModelManager = EntityModelManager.getInstance();

  public UiMockServerApiIndexClassInfo resolve() {

    UiClassFileInfo classFileInfo =
        UiClassFileInfoResolver.builder()
            .className(input.getUiMockServerApiIndexClassName())
            .classNameSuffix(input.getUiMockServerApiIndexClassNameSuffix())
            .classPackagePrefix(input.getUiMockServerApiIndexClassPackagePrefix())
            .rootPackageFullName(input.getUiMockServerApiIndexClassRootPackageFullNamePrefix())
            .sourceCodeRootDir(commonInfo.getSrcDir())
            .fileNameSuffix(".ts")
            .build()
            .resolve();

    return UiMockServerApiIndexClassInfo.builder()
        .info(classFileInfo)
        .mockServerApiClassFullNames(this.getMockServerApiClassFullNames())
        .build();
  }

  private List<String> getMockServerApiClassFullNames() {
    return this.uiMockServerApiClassInfos.stream()
        .map(this::getMockServerApiClassFullName)
        .collect(Collectors.toList());
  }

  private String getMockServerApiClassFullName(UiMockServerApiClassInfo uiMockServerApiClassInfo) {
    Map<String, String> data = new HashMap<>();
    data.put("dirName", this.getMockServerApiClassDirName(uiMockServerApiClassInfo));
    data.put("className", uiMockServerApiClassInfo.getInfo().getUncapitalizeClassName());
    return StringSubstitutor.replace("./${dirName}/${className}", data);
  }

  private String getMockServerApiClassDirName(UiMockServerApiClassInfo uiMockServerApiClassInfo) {
    File file = new File(uiMockServerApiClassInfo.getInfo().getUncapitalizeClassFileFullName());
    return file.getParentFile().getName();
  }
}
